package org.chinacloud.wanghui.jdownload.downloader;

import java.io.*;
import java.net.Socket;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 * User: wanghui
 * Date: 13-10-31
 * Time: 下午5:49
 * To change this template use File | Settings | File Templates.
 */
public class FtpDownloader extends AbstractDownloader{
    private String urlString;
    private String userStrinig = "anonymous";
    private String passwordString = "";

    public void setUserString(String userString){
        this.userStrinig = userString;
    }
    public void setPasswordString(String passwordString){
        this.passwordString = passwordString;
    }

    public FtpDownloader(){}

    public FtpDownloader(String urlString,String savePath){
        this.urlString = urlString;
        super.savePathString = new File(savePath).getAbsolutePath();
    }

    @Override
    protected void saveDownloadState(ObjectOutputStream os) throws IOException {
        os.writeUTF(urlString);
        os.writeUTF(userStrinig);
        os.writeUTF(passwordString);
    }

    @Override
    protected void loadDownloadState(ObjectInputStream is) throws IOException, ClassNotFoundException {
        urlString = is.readUTF();
        userStrinig = is.readUTF();
        passwordString = is.readUTF();
    }


    @Override
    public long getFileLength() {
        try{
            byte[] bytes = new byte[8192];
            URL url = new URL(urlString);
            Socket commandSocket = new Socket(url.getHost());
            InputStream is = commandSocket.getInputStream();
            OutputStream os = commandSocket.getOutputStream();
            int offset = 0;
            offset += is.read(bytes,offset,bytes.length - offset);
            os.write(String.format("USER %s\r\n",userStrinig).getBytes());
            os.flush();
            offset += is.read(bytes,offset,bytes.length - offset);
            os.write(String.format("PASS %s\r\n",passwordString).getBytes());
            os.flush();
            offset += is.read(bytes,offset,bytes.length - offset);
            os.write(String.format("TYPE I\r\n","").getBytes());
            os.flush();
            offset += is.read(bytes,offset,bytes.length - offset);
            commandSocket.getOutputStream().write(String.format("SIZE %s\r\n",url.getPath()).getBytes());
            os.flush();

            try{
                Thread.sleep(100);
            }catch(InterruptedException e){
                System.out.println(e.getMessage());
            }





        }
    }
}
